package com.mallcai.bigdata.ladon.controller.peekdata;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mallcai.bigdata.ladon.controller.peekdata.form.DataImportForm;
import com.mallcai.bigdata.ladon.dpl.entity.peekdata.ImportRecord;
import com.mallcai.bigdata.ladon.service.peekdata.IDataImportService;
import com.mallcai.bigdata.ladon.service.peekdata.IImportRecordService;
import com.mallcai.bigdata.ladon.vo.DataVo;
import com.mallcai.bigdata.ladon.vo.MyPageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 数据导入管理
 * @author feixy
 * @version 1.0
 * @date 2019-07-12 11:23
 */
@RequestMapping("/peekdata")
@RestController
@Slf4j
public class DataImportController {

    @Autowired
    private IDataImportService iDataImportService;

    @Autowired
    private IImportRecordService iImportRecordService;


    @RequestMapping("/import")
    public String importData(DataImportForm form, @RequestParam("file") MultipartFile file ) {
        try{
            iDataImportService.doImport(form.toEntity(), file);
        }catch (Throwable e){
            String message = null;
            if(e instanceof BusinessException){
                message =e.getMessage();
            }
            if(StringUtils.isEmpty(message)){
                message = "数据导入失败, 请查看错误信息";
            }
            log.error(message, e);
            throw new BusinessException(message);
        }
        return "数据导入成功";
    }

    @RequestMapping("/queryImportRecordList")
    public MyPageInfo queryImportRecordList(@RequestBody DataImportForm form) {
        PageHelper.startPage(form.getCurrentPage(), form.getPageSize());
        List<ImportRecord> recordList = iImportRecordService.getByParams(form.getParams());
        PageInfo<ImportRecord> pageInfo = new PageInfo<>(recordList);
        return new MyPageInfo<>(pageInfo);
    }

    @RequestMapping("/previewImportData")
    public DataVo previewImportData(@RequestBody DataImportForm form) {
        try {
            DataVo dataVo = iDataImportService.previewImportData(form.getParams());
            return dataVo;
        }catch (Exception e){
            log.error("", e);
            throw new BusinessException("预览数据失败");
        }
    }

}
